
// components/chart-room/index.ts
const boxHeight = require("../../behavior/play-page-behavior");

Component({
  /**
   * 组件的属性列表
   */
  behaviors: [boxHeight],
  lifetimes: {
    ready: function () {

    },
  },
  pageLifetimes: {

  },
  properties: {
    commentlist: {
      type: Array,
      value: [],
      observer: 'initList'
    },
    addmsg: {
      type: Object,
      value: {},
      observer: 'setList'
    }
  },


  /**
   * 组件的初始数据
   */
  data: {
    unfoldIds: [],
    list: [],
  },

  /**
   * 组件的方法列表
   */
  methods: {

    // 展开评论回复
    unfoldMsg(e?, index?: number) {
      // debugger
      let _i = typeof index == "number" ? index : e.currentTarget.dataset.index;
      const animation = wx.createAnimation({ duration: 200 });
      let isShowChildren = this.data.list[_i].isShowChildren;
      const query = this.createSelectorQuery()
      query.selectAll(".reply-msg").boundingClientRect()
      query.exec((res) => set(res[0][_i].height))
      var set = (height) => {
        if (typeof index == "number") {
          animation.height(height).step();
        } else {
          animation.height(isShowChildren ? 0 : height).step();
        };

        this.setData({
          [`list[${_i}].isShowChildren`]: typeof index == "number" ? true : !this.data.list[_i].isShowChildren,
          [`list[${_i}].animation`]: animation.export()
        });

        let unfoldIds: Array<string> = this.data.unfoldIds;
        if (this.data.list[_i].isShowChildren) {
          unfoldIds.push(this.data.list[_i].Id)
          this.setData({
            unfoldIds
          });
        } else {
          let index = unfoldIds.findIndex((id) => id == this.data.list[_i].Id)
          console.log(index);
          unfoldIds.splice(index, 1)
        }
      }

    },



    // 设置评论列表数据
    initList(val) {
      let list = val.map((ele) => {
        if (this.data.unfoldIds.includes(ele.Id)) {
          ele.isShowChildren = true
        }
        return ele
      });
      this.setData({
        list: list.reverse()
      })
    },
    setList(val) {
      if (Object.values(val).length <= 0) return;
      if (val.ParentId == "") {
        let list: any = this.data.list;
        list.unshift({ ...val, Children: [], isShowChildren: false });
        this.setData({
          list: list,
        });
      } else {
        let targetIndex = this.data.list.findIndex((e: any) => e.Id == val.ParentId);
        let target: any = this.data.list[targetIndex];
        target.Children?.unshift({ ...val });
        this.setData({
          [`list[${targetIndex}]`]: target
        })
        this.unfoldMsg(false, targetIndex);

      }
    },
    setReplyTarget(event) {
      this.triggerEvent("setReplyTarget", { ...event.currentTarget.dataset })
    },
    zoomImage(event) {
      const url = event.currentTarget.dataset.url;
      wx.previewMedia({
        sources: [{ url: url }]
      })
    },
  }
})